package com.atguigu.day4;

import ch.qos.logback.core.util.TimeUtil;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue(3);
        //第一组:抛出异常组
//        blockingQueue.add(3);
//        blockingQueue.add(2);
//        blockingQueue.add(1);
////        blockingQueue.add(4);java.lang.IllegalStateException: Queue full
////        blockingQueue.remove();
////        blockingQueue.remove();
////        blockingQueue.remove();
////        blockingQueue.remove();// java.util.NoSuchElementException
//        System.out.println(blockingQueue.element());


        //第二组:特殊值组
//        System.out.println(blockingQueue.offer(2));
//        System.out.println(blockingQueue.offer(5));
//        System.out.println(blockingQueue.offer(6));
//        System.out.println(blockingQueue.offer(7));

//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());

//        System.out.println(blockingQueue.peek());

        //第三组:一直阻塞
//        try {
//            blockingQueue.put(3);
//            blockingQueue.put(5);
//            blockingQueue.put(9);
//            System.out.println("9已经添加!");
////            blockingQueue.put(1);
////            System.out.println("1已经添加!");
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//
//        try {
//            System.out.println(blockingQueue.take());
//            System.out.println(blockingQueue.take());
//            System.out.println(blockingQueue.take());
//            System.out.println(blockingQueue.take());
//            System.out.println("没执行此代码说明队列阻塞了");
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }


        //第四组:超时退出

        try {
            blockingQueue.offer(3);
            blockingQueue.offer(2);
            blockingQueue.offer(1);
            blockingQueue.offer(4,2, TimeUnit.SECONDS);
            System.out.println("无法插入,超时退出!");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        try {
            blockingQueue.poll();
            blockingQueue.poll();
            blockingQueue.poll();
            blockingQueue.poll(2,TimeUnit.SECONDS);
            System.out.println("无法移除,超时退出!");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
